<template>
  <view @click="handleCloseGuide">
    <topHeader :isShowBack="true" :PageName="'助融报告'"></topHeader>
    <view class="page-bg">
    </view>
    <view>
      <view v-if="!isLogin1">登录/注册</view>
      <view v-else class="msg-box">
        <view class="msg-box-left">
          <view class="avter">
            <image :src="avatar" style="width: 100%;height: 100%"></image>
          </view>
          <view class="msg-box-right">
            <view class="msg-box-right-name">
              <view>{{ username ? username : '用户微信名称' }}</view>
            </view>
            <view class="msg-box-right-phone">手机号：{{ usersInfoObj.phone ? usersInfoObj.phone : '-' }}</view>
          </view>
        </view>
        <view class="guide-wrap">
          <!-- #ifdef MP -->
          <button class="share-btn" open-type="share" :class="{
            light: activetyGuideShow
          }" :disabled="activetyGuideShow">
            分享他人查询
          </button>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <button class="share-btn" @click="shareOther" :class="{light: activetyGuideShow }" :disabled="activetyGuideShow">
            分享他人查询
          </button>
          <!-- #endif -->
          <view v-if="activetyGuideShow" class="guide hlight">
            <view class="guide-circle"></view>
            <span class="guide-hlight">分享他人查询</span>
            <span>领现金红包</span>
          </view>
        </view>
      </view>
    </view>
    <view class="bg_white paddingL15 taxContent" style="position:relative;z-index: ">
      <view style="text-align: center;margin-bottom: 20rpx;font-size: 32rpx;font-weight: 600">税务授权登录</view>
      <view>
        <uv-steps :current="active">
          <uv-steps-item v-for="(item, index) in list1" :key="index">
            <template v-slot:title>
              <view :style="{ color: index == 0 ? '#333' : '#999' }">{{ item.title }}</view>
            </template>
          </uv-steps-item>
        </uv-steps>
      </view>
    </view>
    <view class="mask" @click="closeSelect" v-show="serchList.length && showSelect"> </view>
    <view class="optionsBox" data-origin="select" v-show="serchList.length && showSelect">
      <scroll-view scroll-y style="max-height: 240rpx" @scrolltolower="scrolltolower">
        <view class="option" v-for="(option, index) in serchList" :key="index" @click.stop="selectCompany(option)">
          <view>{{ option.taxpayerName }}</view>
        </view>
        <view class="loading" v-if="serchList.length && searchLoading">
          <uv-loading-icon :show="searchLoading" text="加载数据中...."></uv-loading-icon>
        </view>
      </scroll-view>
    </view>
    <view class="bg_white paddingL15 companyContent">
      <view style="font-size: 30rpx;font-weight: 500;padding-left: 20rpx">公司名称</view>
      <view class="inputStyle" :class="{
        light: activetyGuideShow
      }" style="margin-top: 30rpx">

        <uni-easyinput :class="{
          light: activetyGuideShow
        }" v-if="!isShowAuth" :disabled="activetyGuideShow" v-model="companyTax" @input="searchCompany($event)"
          @click.top placeholder="请输入公司名称或税号" placeholderStyle="'color:#CCCCCC'" :inputBorder="false"></uni-easyinput>

      </view>
      <view class="guide-wrap">
        <button :class="{
          light: activetyGuideShow,
        }" @click="searchTaxFun" :disabled="btnLoading || activetyGuideShow" class="searchTaxBtn" type="primary"
          :loading="btnLoading">查询</button>

        <view v-if="activetyGuideShow" class="guide">
          <view class="guide-circle"></view>
          <span>查询</span>
          <span class="guide-hlight">任意企业信息</span>
          <span>可领现金红包</span>
        </view>
      </view>
    </view>
    <authorize @onLoadFun="onLoadFun" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
    <view v-if="activetyGuideShow" class="cover" @click="handleCloseGuide"></view>
     <share-another v-if="isShareShow" ref="another" @close="isShareShow = false" ></share-another>
  </view>
</template>

<script>
import { shareLoginApi, getEnterpriseSearch } from "@/api/water";
import topHeader from '@/components/topHeader.vue'
import store from "@/store";
import { mapGetters } from 'vuex'
import Routine from "@/libs/routine";
import share from "@/utils/share";
import cache from "@/utils/cache";
import Authorize from "@/components/Authorize.vue";
import shareAnother from "./components/shareAnother.vue"
import { openReportSubscribe } from "@/utils/SubscribeMessage";
import { getPersonalDistributionInfoApi } from '@/api/user.js'
import {loadAnotherBase64} from './base64.js'
export default {
  // computed 属性使用了 Vuex 的 mapGetters 函数，将 isLogin 状态映射为计算属性，以便在组件中使用
  computed: mapGetters(['isLogin', 'activetyGuideShow']),
  components: { Authorize, topHeader , shareAnother},
  // 返回了组件的初始数据
  data() {
    return {
      btnLoading: false,
      isLogin1: true,
      // isChecked: false,
      avatar: '',
      phone: '',
      username: '',
      defaultIcon: '/static/water/defaultuser.png',
      usersInfoObj: {},
      active: 0,
      list1: [{
        title: '公司信息'
      }, {
        title: '税务信息'
      }, {
        title: '获取数据'
      }],
      companyTax: '',
      disabled: false,
      taxpayerName: '',
      isShowAuth: false,
      serchList: [],//模糊查询list
      showSelect: false,//是否显示选择框
      searchLoading: false,
      timeoutId: null,
      where: {
        keyword: "",
        pageNum: 1,
        total: 0,
      },
      globalSpid: '',
      isShareShow: false,
    }
  },
  // #ifdef MP-WEIXIN
  onShareAppMessage: function (res) {
    if (res.from === 'button') { }
    return {
      imageUrl: '../../static/image/indexSharebg.png',
      title: '助融报告',
      path: `/pagesWater/taxSearch/index?spreadUid=${this.usersInfoObj.id}&channelCode=fenxiangtarenchaxun`,
    }
  },
  // #endif
  // 一个异步函数，在组件加载时调用。它从缓存中获取 spreadUid，并将其与传入的选项中的 spreadUid 合并。然后，它检查用户是否已登录，如果未登录，则根据不同的平台（H5、MP、APP-PLUS）导航到登录页面。
  async onLoad(options) {
    if (options.spreadUid) {
      this.globalSpid = options.spreadUid
    }
    this.companyTax = options.taxpayerName

    if (!this.isLogin) {
      // #ifdef H5
      if (Routine.isWeixin()) {
        await this.$wxAuthorize()
        await this.getInfo()
      } else {
        uni.navigateTo({
          url: '/pagesWater/users/login?flagType=0'
        })
      }
      // #endif
      // #ifdef MP || APP-PLUS
      // this.isShowAuth = true
      // #endif
    }
  },
  // 在组件显示时调用。如果用户已登录，它会调用 getInfo 函数获取用户信息，并调用 share.getShareConfig 获取分享配置。
  onShow() {
    if (this.isLogin) {
      this.getInfo()
      this.getPersonalDistributionInfo()
      // #ifdef H5
      share.getShareConfig({}, this.$WXMENU);
      // #endif
    }
  },
  methods: {
    shareOther() {
      this.isShareShow = true
      this.$nextTick(() => {
        this.$refs.another.open({imgbgBase64:loadAnotherBase64 })
      })
    },
    async getPersonalDistributionInfo() {
      let res = await getPersonalDistributionInfoApi();
    },
    handleCloseGuide() {
      this.$store.commit('SET_ACTIVITY_GUIDE_SHOW', true)
    },
    closeSelect() {
      this.showSelect = false;
      this.serchList = []
    },
    selectCompany(v) {
      this.companyTax = v.taxpayerName;
      this.showSelect = false;
    },
    searchCompany(e) {
      // #ifdef MP-WEIXIN
      if (!this.isLogin) return this.isShowAuth = true
      // #endif
      console.log("e", e);
      this.serchList = [];
      this.showSelect = true;
      if (e != this.where.keyword) {
        this.serchList = [];
        this.where.pageNum = 1;
      }
      this.where.keyword = e.trim();
      if (e.length > 2) {
        let reg = /^[^()\/?!\uFF1F\u3001\uFF01]+$/u;
        // const reg2 = /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/
        if (!reg.test(e)) return this.$util.Tips(`请输入正确的公司名称或税号`);
        clearTimeout(this.timeoutId);
        // 设置新的定时器
        this.timeoutId = setTimeout(() => {
          this.getSearchList();
        }, 500);  // 设置防抖的延迟时间（1秒）

      }
    },
    async getSearchList() {
      this.searchLoading = true;
      let res = await getEnterpriseSearch(this.where);
      let data = res.data.list.map((v) => {
        return {
          taxpayerName: v.companyName,
          id: v.establishDate,
        };
      });
      this.serchList = [...this.serchList, ...data];
      this.where.total = res.data.total;
      this.searchLoading = false;
    },
    scrolltolower() {
      if (!this.where.keyword) return;
      if (this.where.pageNum * 10 < this.where.total) {
        this.where.pageNum++;
        this.getSearchList();
      }
    },
    onLoadFun() {
      this.getInfo()
      this.getPersonalDistributionInfo()
    },
    authColse() {
      this.isShowAuth = false
    },
    // 一个异步函数，用于处理公司税务信息的查询。它首先检查公司名称是否为空，然后调用 shareLoginApi 接口查询税号信息，并根据返回结果导航到公司信息页面。
    async searchTaxFun() {
      // #ifdef MP
      if (!this.isLogin) {
        return this.isShowAuth = true
      }
      // #endif
      if (!this.companyTax) {
        return this.$util.Tips("请输入公司名称")
      }
      // #ifdef MP-WEIXIN
      openReportSubscribe().then(() => {
        this.serarchForm()
      })
      // #endif
      // #ifdef H5
      this.serarchForm()
      // #endif

    },

    serarchForm() {
      this.btnLoading = true
      // 税号接口查询
      shareLoginApi({ creditCodeName: this.companyTax.trim() }).then((res) => {
        if (res.code == 200) {
          uni.redirectTo({ url: `/pagesWater/taxSearch/companyInformation?tax=${res.data.creditCodeOrTaxPayerId}&companyName=${res.data.taxpayerName}&provinceName=${res.data.provinceName}&provinceId=${res.data.provinceId}` })
        }
      }).finally(() => {
        this.btnLoading = false
      })

      let params = {
        Um_Key_ButtonName: `查询-${this.companyTax.trim()}`,
        Um_Key_SourcePage: '税务授权登录',
      }
      this.$umaTrack.pageClickTrack(params)
    },


    // 调用 Vuex 的 USERINFO action 获取用户信息，并更新组件的状态。如果获取用户信息失败且错误代码为 401，则导航到登录页面。
    async getInfo() {
      store.dispatch('USERINFO').then(res => {
        this.usersInfoObj = res
        this.username = res.nickname
        let icon = ''
        if (res.icon) {
          icon = res.icon
        } else {
          icon = this.defaultIcon
        }
        this.$set(this, 'avatar', icon)
        this.sexIndex = res.gender
      }).catch(err => {

        if (err.code == 401) {
          uni.navigateTo({
            url: '/pagesWater/users/login'
          })
        }

      })
    },
    // 用于导航到隐私政策页面，根据传入的类型参数构建 URL。
    linkPrivacy(type) {
      uni.navigateTo({
        url: '/pages/privacy/index?privacyType=' + type
      })
    },
  }
}
</script>

<style lang="scss">
.page-bg {
  width: 100vw;
  /* #ifdef MP-WEIXIN */
  height: 535rpx;
  /* #endif */
  /* #ifdef H5 */
  height: 480rpx;
  /* #endif */
  position: absolute;
  left: 0;
  background-color: #488AFD !important;
}

page {}

.cover {
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
  height: 100vh;
  background-color: rgba(#000000, 0.5);
  z-index: 10;
}

.light {
  position: relative;
  z-index: 12;


}

.guide-wrap {
  position: relative;
}

.guide {
  position: absolute;
  z-index: 12;
  top: 190rpx;
  left: 50%;
  transform: translateX(-50%);
  margin: 0 auto;
  height: 115rpx;
  line-height: 115rpx;
  border-radius: 12rpx;
  background-color: #fff;
  font-size: 32rpx;
  padding: 0 32rpx;
  color: #333;
  font-weight: 600;
  white-space: nowrap;

  &-circle {
    position: absolute;
    content: '';
    left: 50%;
    width: 14rpx;
    height: 14rpx;
    background-color: #D4E9FF;
    border-radius: 100%;
    top: -105rpx;
    transform: translateX(-7rpx);
    box-shadow: 0 0 10rpx #D4E9FF;
  }

  &::after {
    position: absolute;
    content: '';
    left: 50%;
    height: 100rpx;
    top: -100rpx;
    border-left: 1rpx dotted #D4E9FF;
  }

  &::before {
    position: absolute;
    content: '';
    top: -35rpx;
    left: 50%;
    transform: translateX(-50%);
    border: 20rpx solid #fff;
    border-color: transparent transparent #fff transparent;

  }

  &-hlight {
    color: #488AFD;
  }

  &.hlight {
    top: 170rpx;
    right: 0;
    left: auto;
    transform: none;
    background: linear-gradient(to right, #fff, #D1E8FF);

    &::before {
      border-bottom-color: #E2EDF8;
    }

    &-hlight {
      color: #488AFD;
    }
  }
}

/deep/ .mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0);
  z-index: 100
}

/* #ifdef MP-TOUTIAO */
/deep/ .uv-steps-item__line--row {
  left: 120rpx !important;
}

/deep/ .uv-steps {
  justify-content: space-between;
}

/* #endif */
.ys {
  margin-left: -5rpx;
  font-size: 24rpx;
  color: #007AFF;
  white-space: nowrap;
}

.taxContent {
  /* #ifdef MP-WEIXIN */
  margin: 280rpx 30rpx 0;
  /* #endif */
  /* #ifdef H5 */
  margin: 160rpx 30rpx 0;
  /* #endif */
  padding-top: 40rpx;
  border-radius: 20rpx;
  padding-bottom: 20rpx;
  height: 244rpx;
}

.companyContent {
  height: calc(100vh - 728rpx);
  padding-top: 30rpx;
  margin: 30rpx;
  border-radius: 20rpx;
}

.searchTaxBtn {
  overflow: hidden;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background: linear-gradient(90deg, #488AFD 0%, #3F9BF9 100%);
  margin: 35rpx auto 0;
  border-radius: 45rpx;
  color: white;

  &.light[disabled] {
    color: white;
    background-color: inherit;
  }
}

.inputStyle {
  width: 100%;
  height: 80rpx;
  background: #F1F5F9;
  border-radius: 30rpx;

}

.msg-box {
  position: relative;
  /* #ifdef MP-WEIXIN */
  top: 220rpx;
  /* #endif */
  /* #ifdef H5 */
  top: 110rpx;
  /* #endif */
  display: flex;
  height: 120rpx;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;

  .msg-box-left {
    display: flex;
  }

  .avter {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    // background-color: pink;
    margin-right: 30rpx;
    overflow: hidden;
  }

  .msg-box-right {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 10rpx 0;

    .msg-box-right-name {
      display: flex;
      align-items: center;

      >view {
        &:nth-child(1) {
          font-weight: 500;
          font-size: 32rpx;
          color: #FFFFFF;
          line-height: 45rpx;
          margin-right: 20rpx;
        }

        &:nth-child(2) {
          background-color: #fff;
          width: 90rpx;
          height: 40rpx;
          line-height: 40rpx;
          border-radius: 20rpx;
          text-align: center;
          font-size: 24rpx;
          color: #488AFD;
        }
      }
    }

    .msg-box-right-phone {
      color: #fff;
    }
  }
}

/deep/ .uni-easyinput {
  width: 95%;
  margin: 0 auto;
}

/deep/ .uni-easyinput__content {
  background: transparent !important;
}

/deep/ .uni-easyinput__content-input {
  height: 80rpx;
}

.optionsBox {
  position: absolute;
  z-index: 10;
  /* #ifdef MP-WEIXIN */
  top: 862rpx;
  /* #endif */
  /* #ifdef H5 */
  top: 730rpx;
  /* #endif */
  left: 30rpx;
  padding: 30rpx 20rpx;
  width: 690rpx;
  border-radius: 10rpx;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  overflow-y: scroll;
  z-index: 1000;

  .option {
    line-height: 40rpx;
    margin-bottom: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &:last-child {
      margin-bottom: 0rpx;
    }

    .delete {
      width: 30rpx;
      height: 30rpx;
    }
  }
}

.share-btn {
  padding-right: 30rpx;
  width: 233rpx;
  height: 58rpx;
  line-height: 58rpx;
  background: #FFFFFF;
  border-radius: 49rpx;
  font-weight: 600;
  font-size: 26rpx;
  color: #488AFD;

  &:disabled {
    color: red;
  }

  &[disabled] {
    color: #488AFD !important;
    background-color: #fff !important;
    opacity: 1;
  }
}
</style>